<template>
  <div>
    <div v-if="upload" class="filter-container">
      <el-button v-permission="['mp:material_upload']" class="filter-item" type="primary" @click="openDialog">新增图文</el-button>
    </div>
    <el-card v-for="(item,index) in list" :key="index" class="fl margin-10 text-center news_card">
      <div class="pic_card">
        <el-image :src="item.cover" :fit="'none'" class="pic"/>
        <div class="title">
          <el-link :href="item.link" type="primary" target="_blank">{{ item.title }}</el-link>
        </div>
      </div>
      <div v-if="!item.more" class="margin-top-10" style="color:#909399;font-size:14px">{{ item.digest }}</div>
      <div v-for="(subItem,subIndex) in item.news" v-else :key="subIndex">
        <el-row class="sub_pic_card margin-top-10">
          <el-col :span="16" class="sub_pic_title">
            <div class="title">
              <el-link :href="subItem.link" type="primary" target="_blank">{{ subItem.title }}</el-link>
            </div>
          </el-col>
          <el-col :span="8">
            <el-image :src="subItem.cover" :fit="'none'" class="pic"/>
          </el-col>
        </el-row>
      </div>
      <div class="margin-top-10">{{ item.createDate }}</div>
      <el-button v-if="selected" type="success" size="mini" class="margin-top-10" icon="el-icon-check" @click="chooseItem(item)">选择</el-button>
      <el-button v-permission="['mp:material_detail']" type="success" size="mini" class="margin-top-10" icon="el-icon-edit" @click="showEdit(item)">编辑</el-button>
      <el-button v-permission="['mp:material_delete']" v-if="deleted" type="success" size="mini" class="margin-top-10" icon="el-icon-delete-solid" @click="removeMaterial(item)">删除</el-button>
    </el-card>
    <div class="clearfix"/>
    <pagination v-permission="['mp:material_list']" v-show="total>0" :total="total" :page.sync="listQuery.pageNo" :limit.sync="listQuery.pageSize" @pagination="initList"/>
    <el-dialog :close-on-click-modal="false" :title="isAdd?'新增图文':'编辑图文'" :visible.sync="dialogVisible" width="60%" top="5vh" append-to-body @close="closeDialog">
      <el-row>
        <el-col :span="6">
          <draggable v-model="newsList" :sort="true" :chosen-class="'chosen'" :animation="1000" @update="resetNewsSeq">
            <transition-group >
              <div v-for="(news,index) in newsList" :key="index" @click="chooseGallery(news)">
                <div v-if="index===0" class="news_items">
                  <img :src="news.cover" class="image">
                  <div class="title">
                    <span>{{ news.title }}</span>
                  </div>
                  <i v-if="isAdd" class="el-icon-delete remove-btn" @click="removeNews(index)"/>
                </div>
                <div v-else class="sub_items">
                  <el-row>
                    <el-col :span="16">
                      <div class="title">{{ news.title }}</div>
                    </el-col>
                    <el-col :span="8">
                      <img :src="news.cover" class="image">
                    </el-col>
                  </el-row>
                  <i v-if="isAdd" class="el-icon-delete remove-btn" @click="removeNews(index)"/>
                </div>
              </div>
            </transition-group>
          </draggable><br>
          <div class="text-center">
            <el-button v-if="isAdd && newsList.length<5" type="success" icon="el-icon-circle-plus-outline" @click="addNews">添加</el-button>
          </div><br>
          <el-alert v-if="newsList.length>1" title="可拖动排序" type="warning"/>
        </el-col>
        <el-col :span="18">
          <el-form v-if="currentNews" ref="newsForm" :rules="rules" :model="currentNews" label-width="80px" class="padding-content">
            <el-form-item label="标题" prop="title">
              <el-input v-model="currentNews.title" placeholder="请输入标题" maxlength="30"/>
            </el-form-item>
            <el-row>
              <el-col :span="6">
                <el-form-item label="作者" prop="author">
                  <el-input v-model="currentNews.author" placeholder="请输入作者名称" maxlength="10"/>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="原文地址" prop="sourceUrl">
                  <el-input v-model="currentNews.sourceUrl" placeholder="请输入图文内容原文地址" maxlength="200"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row>
              <el-col :span="6">
                <el-form-item label="封面">
                  <el-image v-if="currentNews.cover" :src="currentNews.cover" :fit="'fill'"/>
                  <el-button type="success" @click="openPicDialog">图库选择素材</el-button>
                </el-form-item>
              </el-col>
              <el-col :span="18">
                <el-form-item label="摘要" prop="digest">
                  <el-input v-model="currentNews.digest" maxlength="50" type="textarea" rows="5" placeholder="请输入图文摘要"/>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item prop="content">
              <editor v-if="currentNews" ref="newsEditor" :init="editorInit" v-model="currentNews.content"/>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="waiting" @click="closeDialog">取消</el-button>
        <el-button v-permission="['mp:material_upload']" v-if="isAdd" :loading="waiting" type="primary" @click="addMaterial">确定</el-button>
        <el-button v-permission="['mp:material_edit']" v-else :loading="waiting" type="primary" @click="editMaterial">确定</el-button>
      </div>
      <el-dialog :append-to-body="true" :close-on-click-modal="false" :title="'图片素材选择'" :visible.sync="dialogPicVisible" width="75%">
        <mp-material-pic ref="dialogPicComponent" :platform-id="listQuery.platformId" :deleted="false" @choose="choosePic"/>
      </el-dialog>
    </el-dialog>
  </div>
</template>
<script>
import { MpMaterialService } from '@/api/WeChatService'
import MpMaterialPic from '@/views/wechat/mp_material_pic'
import Pagination from '@/components/Pagination'
import Uploader from '@/components/Uploader'
import { CommonService } from '@/api/CommonService'
import { Alert, Notify } from '@/utils/notify'
import Editor from '@tinymce/tinymce-vue'
import draggable from 'vuedraggable'

class News {
  constructor() {
    this.id = 0
    this.sourceUrl = undefined
    this.fileName = undefined
    this.cover = undefined
    this.title = undefined
    this.digest = undefined
    this.content = undefined
    this.author = undefined
    this.type = 'news'
    this.seq = 0
  }
}

export default {
  name: 'WeChatMpMaterialNews',
  components: { Pagination, Uploader, Editor, draggable, MpMaterialPic },
  props: {
    platformId: { type: Number, default: 0 },
    upload: { type: Boolean, default: true },
    selected: { type: Boolean, default: true },
    deleted: { type: Boolean, default: true }
  },
  data() {
    return {
      isAdd: true, list: undefined, total: 0, listLoading: true, dialogVisible: false, waiting: false, dialogPicVisible: false,
      listQuery: { pageNo: 1, pageSize: 20, type: 'news', platformId: this.platformId }, dialogFormVisible: false, newsList: [],
      editorInit: {
        language: 'zh_CN',
        convert_urls: false, height: 300,
        plugins: ['autolink codesample directionality fullscreen hr image link lists media nonbreaking noneditable pagebreak paste preview tabfocus table wordcount'],
        toolbar: ['bold italic underline strikethrough alignleft aligncenter alignright outdent indent undo redo removeformat subscript superscript codesample hr bullist numlist link image forecolor backcolor fullscreen preview'],
        images_upload_handler: function(blobInfo, success, failure) {
          const formData = new FormData()
          formData.append('file', blobInfo.blob())
          CommonService.uploadNewsContentImgMaterial(Editor.platformId, formData).then(res => {
            success(res.url)
          }).catch(() => {
            failure('上传失败，请重新上传')
          })
        }
      },
      currentNews: undefined,
      rules: {
        title: [{ required: true, message: '请输入标题', trigger: 'blur' }],
        digest: [{ required: true, message: '请输入摘要', trigger: 'blur' }],
        content: [{ required: true, message: '请输入内容', trigger: 'blur' }]
      }
    }
  },
  watch: {
    platformId(val) {
      this.listQuery.platformId = val
      this.listQuery.pageNo = 1
      this.list = []
      this.total = 0
    }
  },
  methods: {
    initList() {
      Editor.platformId = this.listQuery.platformId
      this.listLoading = true
      MpMaterialService.getMaterials(this.listQuery).then(response => {
        this.list = response.data
        this.total = response.totalCount
        this.listLoading = false
      })
    },
    chooseItem(data) {
      this.$emit('choose', data)
    },
    openDialog() {
      this.isAdd = true
      this.dialogVisible = true
    },
    closeDialog() {
      this.newsList = []
      this.currentNews = undefined
      this.dialogVisible = false
      this.waiting = false
    },
    addMaterial() {
      if (this.newsList.length === 0) {
        Alert.warn(this, '请填写完整信息!')
        return
      }
      let checked = true
      this.newsList.forEach((news, index) => {
        if (!news.cover) {
          Alert.warn(this, '请选择图文封面!')
          checked = false
          return
        }
      })
      if (!checked) {
        return
      }
      this.$refs['newsForm'].validate(valid => {
        if (valid) {
          this.waiting = true
          MpMaterialService.uploadMaterials(this.newsList).then(() => {
            this.closeDialog()
            this.initList()
          })
        }
      })
    },
    removeMaterial(item) {
      const that = this
      this.$confirm('您确认删除该素材吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        MpMaterialService.deleteMaterial({ platformId: item.platformId, mediaId: item.mediaId }).then(() => {
          that.initList()
          Notify.success(that, '删除成功!')
        })
      }).catch(() => {})
    },
    resetNewsSeq() {
      this.newsList.forEach((news, index) => {
        news.seq = index
      })
    },
    addNews() {
      // 先设置为undefined 重新渲染editor
      this.currentNews = undefined
      const news = new News()
      news.platformId = this.platformId
      this.newsList.push(news)
      this.resetNewsSeq()
      this.$nextTick(() => {
        this.currentNews = news
      })
    },
    removeNews(index) {
      const that = this
      this.$confirm('您确认删除该素材吗?', '提示', { confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning', closeOnClickModal: false }).then(() => {
        that.newsList.splice(index, 1)
        that.currentNews = undefined
        that.resetNewsSeq()
      }).catch(() => {})
    },
    chooseGallery(data) {
      this.currentNews = data
    },
    choosePic(data) {
      this.currentNews.cover = data.cover
      this.currentNews.fileName = data.mediaId
      this.dialogPicVisible = false
    },
    openPicDialog() {
      this.dialogPicVisible = true
      this.$nextTick(() => {
        this.$refs.dialogPicComponent.initList()
      })
    },
    showEdit(item) {
      this.isAdd = false
      this.dialogVisible = true
      MpMaterialService.getNewsMaterialInfo({ platformId: this.platformId, mediaId: item.mediaId }).then(result => {
        this.newsList = result
        if (this.newsList) {
          this.currentNews = this.newsList[0]
        }
      })
    },
    editMaterial() {
      if (this.newsList.length === 0) {
        Alert.warn(this, '请填写完整信息!')
        return
      }
      let checked = true
      this.newsList.forEach((news, index) => {
        if (!news.cover) {
          Alert.warn(this, '请选择图文封面!')
          checked = false
          return
        }
      })
      if (!checked) {
        return
      }
      this.$refs['newsForm'].validate(valid => {
        if (valid) {
          this.waiting = true
          MpMaterialService.editMaterials(this.newsList).then(() => {
            this.closeDialog()
            this.initList()
          })
        }
      })
    }
  }
}
</script>
<style lang="scss">
  .news_card{width:320px;padding:0px;
    .pic_card {
      position: relative;
      .pic {width: 100%;height: 120px;display: block;}
      .title{position: absolute;bottom: 0;background: #0000006e;color: #ffffff;width: 100%;display: flex;align-items: center;justify-content: center;padding:10px 0;}
    }
    .sub_pic_card{
      border-bottom: 1px solid #dcdfe6;padding-bottom:5px;
      .sub_pic_title{display: table;height: 100px;}
      .pic {width: 100%;display: block;}
      .title{display: table-cell;vertical-align: middle;padding:5px;}
    }
    .el-card__body{padding:5px;} }

  .news_items{
    cursor: move;
    position: relative;
    img{width: 100%;height:150px}
    .title{color:#ffffff;height:30px;line-height:30px;width:100%;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;position: absolute;bottom:3px;background:#00000061; span{margin:10px;}}
    .remove-btn{position:absolute;top:35%;right:5%;font-size:1.5em;cursor:pointer;}
  }
  .sub_items{
      position: relative;
      height:100px;overflow:hidden;border-bottom: 1px solid #cccccc;cursor: move;
      .title{display: flex;align-items: center;justify-content: center;height: 100px;}
      img{max-height:100px;width:100%;}
      .remove-btn{position:absolute;top:35%;right:5%;font-size:1.5em;cursor:pointer;}
    }
  .chosen{
    border:2px dashed #cccccc;
  }
</style>
